package cn.ac.iie.config;

import com.clickhouse.jdbc.ClickHouseDataSource;
import java.sql.SQLException;
import java.util.Properties;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.core.JdbcTemplate;

@Configuration
public class DoubleDataSource {

  @Value("${spring.datasource.clickhouse.url}")
  private String url;

  @Value("${spring.datasource.clickhouse.username}")
  private String user;

  @Value("${spring.datasource.clickhouse.password}")
  private String password;

  @Bean
  @Primary
  @ConfigurationProperties(prefix = "spring.datasource")
  public DataSource mySqlDataSource() {
    return DataSourceBuilder.create().build();
  }

  /** MySql 数据源配置. */
  @Bean(name = "mysqlTemplate")
  public JdbcTemplate mysqlTemplate() {
    return new JdbcTemplate(mySqlDataSource());
  }

  /** ClickHouse 数据源配置. */
  @Bean(name = "clickHouseDataSource")
  public DataSource clickHouseDataSource() throws SQLException {
    final Properties properties = new Properties();
    properties.setProperty("user", user);
    properties.setProperty("password", password);
    return new ClickHouseDataSource(url, properties);
  }

  /** ClickHouse 数据源配置. */
  @Bean(name = "clickHouseTemplate")
  public JdbcTemplate clickHouseTemplate() throws SQLException {
    return new JdbcTemplate(clickHouseDataSource());
  }
}
